package com.platform.zuul.filter;

import com.apache.exception.BusinessException;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SEND_ERROR_FILTER_ORDER;

/**
 * description: 统一异常过滤器
 *
 * @author dyh 创建时间：2018年03月19日
 */
@Component
public class ErrorFilter extends ZuulFilter {

    Logger log = Logger.getLogger(getClass());
    protected static final String SEND_ERROR_FILTER_RAN = "sendErrorFilter.ran";

    @Override
    public String filterType() {
        return FilterConstants.ERROR_TYPE;
    }

    @Override
    public int filterOrder() {
        return SEND_ERROR_FILTER_ORDER;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        return ctx.getThrowable() != null
                && !ctx.getBoolean(SEND_ERROR_FILTER_RAN, false);
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        Throwable throwable = ctx.getThrowable();
        JSONObject errorBean = new JSONObject();
        String message = throwable.getCause().getMessage();
        if("2011".equals(message)){
            errorBean.put("msg","您已登录，请不要重复登录");
            errorBean.put("flag","F");
        } else {
            errorBean.put("errorMesage", "非法访问");
            errorBean.put("errorCode", "2010");
        }

        if(throwable.getCause() instanceof BusinessException){
            log.error("this is a ErrorFilter :"+message);
        } else {
            log.error("this is a ErrorFilter :"+throwable.getCause());
        }
        try {
            HttpServletResponse response = ctx.getResponse();
            response.setContentType("application/json; charset=utf8");
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            PrintWriter writer = null;
            try {
                writer = response.getWriter();
                writer.print(errorBean.toString());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(writer!=null){
                    writer.close();
                }
            }
        } catch (Exception var5) {
            ReflectionUtils.rethrowRuntimeException(var5);
        }
        return null;
    }
}